package com.book.service.Impl;

import com.book.dao.BookMapper;
import com.book.dao.StudentMapper;
import com.book.entity.Book;
import com.book.entity.Lend;
import com.book.entity.Student;
import com.book.service.BookService;
import com.book.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.*;
import java.util.stream.Collectors;

public class BookServiceImpl implements BookService {
    @Override
    public List<Lend> getLendList() {
        try (SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper mapper = sqlSession.getMapper(BookMapper.class);
            return mapper.getLendList();
        }
    }

    @Override
    public void returnBook(String l_id) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper mapper = sqlSession.getMapper(BookMapper.class);
            mapper.deleteLend(l_id);
        }
    }

    @Override
    public List<Book> getActiveBookList() {
        Set<Integer> set = new HashSet<>();
        this.getLendList().forEach(lend -> set.add(lend.getBID()));
        try (SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper mapper = sqlSession.getMapper(BookMapper.class);
            return mapper.getBookList()
                    .stream()
                    .filter(book -> !set.contains(book.getB_id()))
                    .collect(Collectors.toList());
        }
    }



    @Override
    public List<Student> getStudentList() {
        try (SqlSession sqlSession = MybatisUtil.getSession()){
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            return mapper.getStudentList();
        }
    }

    @Override
    public void addLend(int s_id, int b_id) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper mapper = sqlSession.getMapper(BookMapper.class);
            mapper.addLend(s_id,b_id);
        }
    }

    @Override
    public Map<Book,Boolean> getAllBook() {
        Set<Integer> set = new HashSet<>();
        this.getLendList().forEach(lend -> set.add(lend.getBID()));
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            Map<Book,Boolean> map = new LinkedHashMap<>();
            BookMapper mapper = sqlSession.getMapper(BookMapper.class);
            mapper.getBookList().forEach(book -> map.put(book,set.contains(book.getB_id())));
            return map;
        }
    }

    @Override
    public void deleteBook(int b_id) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper mapper = sqlSession.getMapper(BookMapper.class);
            mapper.deleteBook(b_id);
        }
    }

    @Override
    public void addBook(String b_name, Double b_price) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper mapper = sqlSession.getMapper(BookMapper.class);
            mapper.addBook(b_name,b_price);
        }
    }
}
